﻿/**
 * File name:      UserManageService.java
 * Date:           2013-4-10
 * Description:    // 用于详细说明此程序文件完成的主要功
 *                 // 能与其他模块或函数的接口，输出值、
 *                 // 取值范围、含义及参数间的关系
 * Modify History:     Date             Programmer       Notes
 *                    ---------        ---------------  ---------
 *                    2013-4-10            胡少磊                           Initial
 **********************************************************************/
package com.wy.framework.services.user;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;

import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.wy.business.developer.developer.services.RegistService;
import com.wy.component.communication.HTTPClientUtils;
import com.wy.component.dataConvert.Base64Image;
import com.wy.component.dataConvert.BeanUtil;
import com.wy.component.dataConvert.DateUtil;
import com.wy.component.easemob.httpclient.apidemo.EasemobIMUsers;
import com.wy.component.properties.PropertiesUtil;
import com.wy.component.security.DescUtil;
import com.wy.component.wxUtils.ParamesAPI;
import com.wy.component.wxUtils.WeixinUtil;
import com.wy.framework.constants.Constants;
import com.wy.framework.constants.DBConstant;
import com.wy.framework.constants.FieldConstant;
import com.wy.framework.constants.RtnCodeConstant;
import com.wy.framework.dao.ErrorSqlException;
import com.wy.framework.exceptions.ServiceException;
import com.wy.framework.pojos.TSysConfig;
import com.wy.framework.pojos.TSysOrginfo;
import com.wy.framework.pojos.TSysUserinfo;
import com.wy.framework.pojos.TSysUserroles;
import com.wy.framework.services.AbstractBaseService;
import com.wy.framework.services.login.LoginService;

/**
 * Created on 2013-4-10
 * <p>
 * Title: [用户管理]
 * </p>
 * <p>
 * Description: 用户管理相关功能,默认user为报送用户monitor为监管用户
 * </p>
 * 
 * @version 1.0
 */
public class UserManageService extends AbstractBaseService {
	private static Logger logger = LoggerFactory.getLogger(UserManageService.class);
	
	@Autowired
	private LoginService loginService;
	@Autowired
	private RegistService registService;
	Session session;
	Transaction transaction;
	PropertiesUtil p = new PropertiesUtil();
	
	/**
	 * 开始事务
	 * @throws ErrorSqlException 
	 * @throws HibernateException 
	 */
	private void beginTransaction() {
		try {
			session = dataBaseDao.getHibernateTemplate().getSessionFactory().openSession();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
//		if(transaction==null || !transaction.isActive() || transaction.wasCommitted() || transaction.wasRolledBack())
		transaction=session.beginTransaction();
	}

	/**
	 * 关闭事务
	 * @param isSuccess
	 */
	private void endTransaction(boolean isSuccess) {
		if(!isSuccess){
			transaction.rollback();
			return;
		}
		session.flush();
		session.clear();
		transaction.commit();
		session.close();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Map queryUserInfo(String orgCode, TSysUserinfo loginUser,int rows,int page, String searchVal ,String orderparam) throws ServiceException {
		if(StringUtils.isBlank(searchVal))
			searchVal = "";
		try {
			Map result =  new HashMap();
			List<Map> userInfoList = new ArrayList<Map>();
			String userAccount = ServletActionContext.getRequest().getParameter("userAccount");
			List params=new ArrayList();
			params.add(Constants.VERIFY_NOT);
			params.add(Constants.VERIFY_PASS);
			params.add(Constants.VERIFY_REJECT);
			params.add(Constants.VERIFY_PERFECT);
			//从首页待审进入
			if(StringUtils.isNotEmpty(userAccount)){
				params.add(userAccount);
				params.add("%"+searchVal+"%");
				params.add("%"+searchVal+"%");
				params.add("%"+searchVal+"%");
				int count = dataBaseDao.queryForInt("Tc_Sys_Userinfo.countuserByuserAccount", params);
				result.put("total", count);
				params.add(rows*(page-1));
				params.add(rows);
				userInfoList=this.dataBaseDao.queryForList("Tc_Sys_Userinfo.queryuserByuserAccount", params);
				System.out.println("---------------------------------"+params.toArray().toString());
				System.out.println("---------------------------------"+userInfoList.toArray().toString());
			}
			//超管登录
			else if(StringUtils.equals(loginUser.getUserId(), "admin") && StringUtils.isEmpty(userAccount)){
				params.add("%"+searchVal+"%");
				params.add("%"+searchVal+"%");
				params.add("%"+searchVal+"%");
				params.add(orgCode);
				params.add(orgCode);
				int count = dataBaseDao.queryForInt("Tc_Sys_Userinfo.countQueryuserdmin",params);
				result.put("total", count);
				params.add(rows*(page-1));
				params.add(rows);
				userInfoList=this.dataBaseDao.queryForList("Tc_Sys_Userinfo.queryuserdmin",params);
			}
			//点击部门树节点
			else if (StringUtils.isNotEmpty(orgCode) && StringUtils.isEmpty(userAccount)) {
				params.add("%"+searchVal+"%");
				params.add("%"+searchVal+"%");
				params.add("%"+searchVal+"%");
				params.add(orgCode);
				int count = dataBaseDao.queryForInt("Tc_Sys_Userinfo.countQueryuserByorgCode", params);
				result.put("total", count);
				params.add(rows*(page-1));
				params.add(rows);
				userInfoList=this.dataBaseDao.queryForListOrder("Tc_Sys_Userinfo.queryuserByorgCode", params,orderparam);
			}
			
			List<Map> userInfoMapList = new ArrayList<Map>();
			for (Map userInfo : userInfoList) {
				msgSourceAdapter.translateMap(userInfo,
						FieldConstant.isAvailable);
				msgSourceAdapter.translateMap(userInfo, FieldConstant.outFlag);
				Map<String, Object> row = new HashMap<String, Object>();
				row.put("userInfo", userInfo);
				userInfoMapList.add(row);
			}
			result.put("userInfoMapList", userInfoMapList);
			return result;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}
	
	public List<Map> queryUserRole(String userAccount) throws ServiceException {
		try {
			return this.dataBaseDao.queryForList("tc_sys_userroles.list", userAccount);
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Map> queryUserInfoExport(String param, String orgCode)
			throws ServiceException {
		try {
			List params = new ArrayList();
			params.add("%" + param + "%");
			params.add("%" + param + "%");
			params.add("%" + param + "%");
			params.add(orgCode);
			params.add(orgCode);
			return this.dataBaseDao.queryForList("Tc_Sys_UserInfo.queryUserInfoExport", params);
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	@SuppressWarnings("rawtypes")
	public List<Map> queryUserInfoExport(String orgCode)
			throws ServiceException {
		try {
			List param=new ArrayList();
			param.add(Constants.VERIFY_NOT);
			param.add(Constants.VERIFY_PASS);
			param.add(Constants.VERIFY_REJECT);
			param.add(Constants.VERIFY_PERFECT);
			param.add(orgCode);
			param.add(orgCode);
			return this.dataBaseDao.queryForList("Tc_Sys_Userinfo.queryuserByorgCodeT", param);
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			// e.printStackTrace();
			throw new ServiceException(e);
		}
	}



	@Override
	public String querySysConfigById(String configKey) throws ServiceException {
		String rspCode = null;
		String rspMsg = null;
		TSysConfig sysConfig = null;
		try {
			sysConfig = (TSysConfig) this.getDataBaseDao().load(
					TSysConfig.class, configKey);

			if (null == sysConfig
					|| sysConfig.getIsAvailable().equals(
							DBConstant.DB_STATUS_DISABLCE)) {
				rspCode = RtnCodeConstant.RTN_CODE_SEARCH_RESULT_EMPTY;
				rspMsg = msgSourceAdapter.getMessage(rspCode);
				throw new ServiceException(rspCode, rspMsg);
			}

		} catch (ErrorSqlException e) {
			e.printStackTrace();
			rspCode = RtnCodeConstant.RTN_CODE_UNKNOW_ERROR;
			rspMsg = msgSourceAdapter.getMessage(rspCode);
			throw new ServiceException(rspCode, rspMsg, e);
		}
		return sysConfig.getConfigValue();
	}
	


	/**
	 * 删除账户
	 * 
	 * @param userAccount
	 * @return
	 * @throws ServiceException
	 */
	public String deleteUser(String userId) throws ServiceException {
		try {
			dataBaseDao.update("t_sys_userinfo.del",userId);
			dataBaseDao.update("t_sys_userroles.del",userId);
			
			return RtnCodeConstant.RTN_CODE_SUCCESS;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}
	
	
	public String saveHead(String dataURL,String headRootPath,String headPathBody)throws ServiceException{
		Base64Image.GenerateImage(dataURL, headRootPath + headPathBody);
		return  RtnCodeConstant.RTN_CODE_SUCCESS;
	}

   /**
    *后端新增用户
    * Function Name               saveUserInfo                                   
    * @param userInfo
    * @return
    * @throws ServiceException          		             
    * @description TODO(这里用一句话描述这个方法的作用 – 可选)
    * Modify History:              Date             Programmer       Notes
    *                            ---------        ---------------  ---------
    *                      2016-3-22 上午10:59:53           高振泰                     Initial
    **********************************************************************
    */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String saveUserInfo(TSysUserinfo userInfo)throws ServiceException {
		String head=ServletActionContext.getRequest().getParameter("head");
		String addRoleData=ServletActionContext.getRequest().getParameter("addRoleData");
		String [] rolesData=addRoleData.split(",");
		List params=new ArrayList();
		try {
			params.add(userInfo.getUserId());
			int count=dataBaseDao.queryForInt("t_sys_userinfo.ctn31", params);
			if(count>0){
				dataBaseDao.delete(userInfo);
				dataBaseDao.update("t_sys_userroles.physicalDel",params);
			}
			// 设置初始密码
			userInfo.setUserPassword(querySysConfigById(DBConstant.SYS_CONFIG_INIT_PASSWORD));
			// 设置更新时间
			userInfo.flushUpdateTime();
			// 保存用户角色信息
			TSysUserroles userRoles = new TSysUserroles();
			if(!StringUtils.equals(head, "")){
				head=head.substring(head.lastIndexOf("/upload"));
				userInfo.setPhotoUrl(head);
			}else{
				userInfo.setPhotoUrl(registService.genDefaultHeadImg(userInfo.getUserId()));
			}
			userInfo.setIsAvailable(Constants.IS_AVAILABLE);
			userInfo.setOperatorAccount(loginUser().getUserId());
			userInfo.setOperatorName(loginUser().getUserName());
			userInfo.setCreateTime(new Date());
			dataBaseDao.save(userInfo);
			
			for(int i=0;i<rolesData.length;i++){
				userRoles.setUserRoleId(UUID.randomUUID().toString());
				userRoles.setUserId(userInfo.getUserId());
				userRoles.setRoleId(rolesData[i]);
				userRoles.flushUpdateTime();
				userRoles.setOperatorAccount(loginUser().getUserId());
				userRoles.setOperatorName(loginUser().getUserName());
				userRoles.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
				dataBaseDao.getHibernateTemplate().merge(userRoles);
			}
			
			final String userId=userInfo.getUserId();
			final String roleId=userInfo.getRoleId();
			final String userName=userInfo.getUserName();
			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					/**
					 * 环信注册IM用户[单个]
					 */
					try {
				       ObjectNode datanode = JsonNodeFactory.instance.objectNode();
					   datanode.put("username",EasemobIMUsers.convertUsernameForDeveloper(userId));
					   List listTSysOrgroles;
						listTSysOrgroles = dataBaseDao.queryNoKeyForList("select o.orgname from T_Sys_Orgroles t,t_sys_orginfo o where t.orgcode=o.orgcode and t.roleId='"+roleId+"' ",null);
					    //app开发者无机构
						if(listTSysOrgroles==null || listTSysOrgroles.size()==0){
							datanode.put("nickname",userName + "_APP开发者");
						}else{
							Map m = (Map) listTSysOrgroles.get(0);
							datanode.put("nickname",userName + "_" + m.get("orgname"));
						}
						datanode.put("password", Constants.DEFAULT_PASSWORD);
						ObjectNode createNewIMUserSingleNode = EasemobIMUsers.createNewIMUserSingle(datanode);
						if (null != createNewIMUserSingleNode) {
							logger.info("注册IM用户[单个]: " + createNewIMUserSingleNode.toString());
						}
					} catch (ErrorSqlException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
			Thread thread = new Thread(runnable);//线程创建
			thread.start();//线程启动
			
			return RtnCodeConstant.RTN_CODE_SUCCESS;
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 更新用户信息
	 * @param tcSysUserInfo 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String updateUserInfo(TSysUserinfo tSysUserinfoParam)
			throws ServiceException {
		String head = ServletActionContext.getRequest().getParameter("head");
		String addRoleData = ServletActionContext.getRequest().getParameter(
				"addRoleData");
		try {
			List<Map> list = dataBaseDao.queryForList(
					"t_sys_userinfo.password", tSysUserinfoParam.getUserId());
			TSysUserinfo tSysUserinfoDb = (TSysUserinfo) dataBaseDao.load(
					TSysUserinfo.class, tSysUserinfoParam.getUserId());
			if (!StringUtils.equals(head, "")) {
				head = head.substring(head.lastIndexOf("/upload"));
				tSysUserinfoDb.setPhotoUrl(head);
			}
			tSysUserinfoDb.setUserName(tSysUserinfoParam.getUserName());
			tSysUserinfoDb.setEmail(tSysUserinfoParam.getEmail());
			tSysUserinfoDb.setWechat(tSysUserinfoParam.getWechat());
			tSysUserinfoDb.setGender(tSysUserinfoParam.getGender());
			tSysUserinfoDb.setJobPosition(tSysUserinfoParam.getJobPosition());
			tSysUserinfoDb.setUserPassword((String) list.get(0).get(
					"USERPASSWORD"));
			tSysUserinfoDb.setCreateTime(new Date());
			tSysUserinfoDb.flushUpdateTime();
			if (StringUtils.isEmpty(tSysUserinfoParam.getIsAvailable())) {
				tSysUserinfoDb.setIsAvailable(Constants.IS_AVAILABLE);
			}
			tSysUserinfoDb.setOperatorName(loginUser().getUserName());
			tSysUserinfoDb.setOperatorAccount(loginUser().getUserId());
			dataBaseDao.update(tSysUserinfoDb);

			if (!StringUtils.equals(null, addRoleData)) {
				dataBaseDao.update("t_sys_userroles.del",
						tSysUserinfoParam.getUserId());
				String[] rolesData = addRoleData.split(",");
				for (int i = 0; i < rolesData.length; i++) {
					TSysUserroles userRoles = new TSysUserroles();
					userRoles.setUserRoleId(UUID.randomUUID().toString());
					userRoles.setUserId(tSysUserinfoParam.getUserId());
					userRoles.setRoleId(rolesData[i]);
					userRoles.flushUpdateTime();
					userRoles.setOperatorAccount(loginUser().getUserId());
					userRoles.setOperatorName(loginUser().getUserName());
					if (StringUtils.isEmpty(userRoles.getIsAvailable())) {
						userRoles.setIsAvailable(Constants.IS_AVAILABLE);
					} else {
						userRoles.setIsAvailable(Constants.IS_NOT_AVAILABLE);
					}
					dataBaseDao.save(userRoles);
				}
			}

			final String userId = tSysUserinfoParam.getUserId();
			final String roleId = tSysUserinfoParam.getRoleId();
			final String userName = tSysUserinfoParam.getUserName();
			Thread t = new Thread() {
				public void run() {
					/**
					 * 环信注册IM用户[单个]
					 */
					try {
						ObjectNode datanode = JsonNodeFactory.instance
								.objectNode();
						datanode.put("username", EasemobIMUsers
								.convertUsernameForDeveloper(userId));
						List listTSysOrgroles;
						listTSysOrgroles = dataBaseDao
								.queryNoKeyForList(
										"select o.orgname from T_Sys_Orgroles t,t_sys_orginfo o where t.orgcode=o.orgcode and t.roleId='"
												+ roleId + "' ", null);
						// app开发者无机构
						if (listTSysOrgroles == null
								|| listTSysOrgroles.size() == 0) {
							datanode.put("nickname", userName + "_APP开发者");
						} else {
							Map m = (Map) listTSysOrgroles.get(0);
							datanode.put("nickname",
									userName + "_" + m.get("orgname"));
						}
						datanode.put("password", Constants.DEFAULT_PASSWORD);
						ObjectNode createNewIMUserSingleNode = EasemobIMUsers
								.createNewIMUserSingle(datanode);
						if (null != createNewIMUserSingleNode) {
							logger.info("注册IM用户[单个]: "
									+ createNewIMUserSingleNode.toString());
						}

						String username = EasemobIMUsers
								.convertUsernameForDeveloper(userId);
						ObjectNode json2 = JsonNodeFactory.instance
								.objectNode();
						// app开发者无机构
						if (listTSysOrgroles == null
								|| listTSysOrgroles.size() == 0) {
							json2.put("nickname", userName + "_APP开发者");
						} else {
							Map m = (Map) listTSysOrgroles.get(0);
							json2.put("nickname",
									userName + "_" + m.get("orgname"));
						}
						ObjectNode modifyIMUserNicknameWithAdminTokenNode = EasemobIMUsers
								.modifyIMUserNicknameWithAdminToken(username,
										json2);
						if (null != modifyIMUserNicknameWithAdminTokenNode) {
							logger.info("修改IM用户昵称 提供管理员token: "
									+ modifyIMUserNicknameWithAdminTokenNode
											.toString());
						}
					} catch (ErrorSqlException e) {
						e.printStackTrace();
					}
				}
			};
			t.start();

		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}

		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}
	


	private String removeHeadDouHao(String stationName) {
		if(StringUtils.isNotEmpty(stationName) && StringUtils.equals(stationName.substring(0,1), ",")){
			stationName = stationName.substring(1);
			return removeHeadDouHao(stationName);
		}
		else
			return stationName;
	}

	/**
	 * 删除用户现有角色信息
	 */
	private void deleteUserRoles(String userAccount)
			throws DataAccessException, ErrorSqlException {
		dataBaseDao
				.getHibernateTemplate()
				.bulkUpdate("update TcSysUserRoles set isAvailable=?,updateTime=? where userAccount=?",
						new Object[] { DBConstant.DB_STATUS_DISABLCE,
								DateUtil.getCurrentDateTime(), userAccount });
	}

	/**
	 * 用户解锁:将用户从注销或锁定状态改为可用
	 */
	public void resetUserState(String userAccount) throws ServiceException {
		try {
			TSysUserinfo userInfoIndb = (TSysUserinfo) dataBaseDao.load(
					TSysUserinfo.class, userAccount);
			userInfoIndb.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
			userInfoIndb.flushUpdateTime();
			logger.info("重置用户状态为可用");
			dataBaseDao.getHibernateTemplate().update(userInfoIndb);
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			// e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 修改密码
	 */
	public String updatePwd(String newPassword) throws ServiceException {
		try {
			TSysUserinfo userInfoIndb = null;
			userInfoIndb = (TSysUserinfo) this.getDataBaseDao().load(TSysUserinfo.class, loginUser().getUserId());
		
			if (userInfoIndb != null) {
					String encryptNewPwd = DescUtil.encrypt(newPassword);
					userInfoIndb.setUserPassword(encryptNewPwd);
					userInfoIndb.flushUpdateTime();
					logger.info("保存新的密码信息");
					dataBaseDao.getHibernateTemplate().merge(userInfoIndb);
					return RtnCodeConstant.RTN_CODE_SUCCESS;
			}
			logger.info("用户名、密码验证不通过");
			return RtnCodeConstant.RTN_CODE_D06_USER_ERROR;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}

	/**
	 * 重置用户密码为初始密码
	 */
	public String updateResetPwd(String userId) throws ServiceException {
		try {
			TSysUserinfo userInfoIndb = (TSysUserinfo) dataBaseDao.load(TSysUserinfo.class, userId);
			userInfoIndb.setUserPassword(querySysConfigById(DBConstant.SYS_CONFIG_INIT_PASSWORD));
			userInfoIndb.flushUpdateTime();
			dataBaseDao.getHibernateTemplate().update(userInfoIndb);
			return DescUtil.decrypt(userInfoIndb.getUserPassword());
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			// e.printStackTrace();
			throw new ServiceException(e);
		}
	    
	}

	/**
	 * 用户信息修改
	 */

	public String modifyUser(TSysUserinfo userInfo) throws ServiceException {
		try {
			TSysUserinfo userInfoIndb = (TSysUserinfo) this.getDataBaseDao()
					.load(TSysUserinfo.class, userInfo.getUserId());
			BeanUtils.copyProperties(userInfoIndb, userInfo, new String[] {
					"userName", "telephoneNo", "mobileNo", "email" });
			userInfo.flushUpdateTime();
			dataBaseDao.getHibernateTemplate().merge(userInfo);
			return RtnCodeConstant.RTN_CODE_SUCCESS;
		} catch (Exception e) {
			logger.error("系统错误:{}", e);
			// e.printStackTrace();
			throw new ServiceException(e);
		}
	}

	/**
	 * 查询所有用户信息
	 */
	public Map queryAllUserInfo() throws ServiceException {
		Map userMap = new HashMap();
		try {
			List<Map> userInfoList = dataBaseDao.queryForList("TC_SYS_USERINFO.queryAllUser");
			for (Map map : userInfoList) {
				userMap.put(map.get("userAccount"), map);
			}
		} catch (ErrorSqlException e) {
			logger.error("系统错误:{}", e);
			// e.printStackTrace();
			throw new ServiceException(e);
		}
		return userMap;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Map> loadUser(String userId) throws ErrorSqlException {
		List<Map> result =null;
		List param=new ArrayList();
		param.add(userId);
		result=dataBaseDao.queryForList("tc_sys_userinfo.loadUser",param);
		return result;
	}
	
	/**
	 * 
	 * Function Name               getAllOrgInfo                                   
	 * @return
	 * @throws Exception          		             
	 * @description 查询所有部门数据 返回list
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-6-6 上午10:16:12           黄忠                     Initial
	 **********************************************************************
	 */
	public List getAllOrgInfo() throws Exception {
		return dataBaseDao.queryForList("t_sys_orgcode.loadOrgAllInfoList");
	}

	public List<Map> loadAllUser() throws ErrorSqlException {
		List<Map> result = dataBaseDao.queryForList("tc_sys_userinfo.loadAllUser");
		return result;
	}

	public List queryQrCodeForUser(String userAccount) throws ErrorSqlException {
		List params = new ArrayList();
		params.add(userAccount);
		List list = dataBaseDao.queryForList("tc_sys_userinfo.queryQrCodeForUser", params);
		return list;
	}
	
	public List queryVerifyInfo(String userAccount) throws ErrorSqlException {
		List params = new ArrayList();
		params.add(userAccount);
		List<Map> list = dataBaseDao.queryForList("tc_sys_userinfo.queryVerifyInfo", params);
		Map map = new HashMap();
		if(list!=null && list.size()>0){
			if (StringUtils.equals(list.get(0).get("status")==null?"":list.get(0).get("status").toString(), "0")) {
				map.put("text", "待审核");
				list.get(0).putAll(map);
			}
			else if (StringUtils.equals(list.get(0).get("status")==null?"":list.get(0).get("status").toString(), "1")) {
				map.put("text", "通过");
				list.get(0).putAll(map);
			}
			else if (StringUtils.equals(list.get(0).get("status")==null?"":list.get(0).get("status").toString(), "2")) {
				map.put("text", "驳回");
				list.get(0).putAll(map);
			}else{
				map.put("text", "待完善资料");
				map.put("status", Constants.VERIFY_PERFECT);
				list.get(0).putAll(map);
			}
		}
		return list;
	}

	public List fuzzyQueryUserInfo(String name, String confferenceId)
			throws ErrorSqlException {
		List params = new ArrayList();
		params.add(confferenceId);
		params.add(confferenceId);
		params.add(confferenceId);
		params.add(confferenceId);
		params.add(confferenceId);
		String tempSql = "";
		if(StringUtils.isNotBlank(name)){
			tempSql = "  AND (r.name LIKE ? or r.mobile LIKE ?)";
			params.add(name);
			params.add(name);
		}
		return dataBaseDao.queryForList("TB_Confference_Roster.fuzzyQueryUserInfo", params,tempSql);
	}

	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Map> loadTreeUser(String orgCode)throws ServiceException,ErrorSqlException{
		List<Map> result;
		if(StringUtils.equals("-1", orgCode) || StringUtils.isEmpty(orgCode) || StringUtils.equals(orgCode, "000000")){
			result=this.dataBaseDao.queryForList("TC_Sys_OrgInfo.loadRootOrgAllUser");
		}
		else{
			ArrayList param = new ArrayList();
			param.add(orgCode);
			result=this.dataBaseDao.queryForList("TC_Sys_OrgInfo.loadRootOrgUser",param);
		}
		return BeanUtil.listToTree(result, "id", "pid");
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public boolean checkPhoneExist(String phone) throws ServiceException{
		try {
			List list=dataBaseDao.queryForList("tc_sys_userinfo.checkPhoneExist", phone);
			boolean result=list.size()>0?true:false;
			return result;
		} catch (ErrorSqlException e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}
	
	public String updateUserInfo(String userAccount, String property, String content) throws ServiceException{
		try {
			String sql="UPDATE tc_sys_userinfo n SET "+property+"='"+content+"' WHERE n.userAccount='"+userAccount+"'";
			this.dataBaseDao.execute(sql);
			return RtnCodeConstant.RTN_CODE_SUCCESS;
		} catch (ErrorSqlException e) {
			logger.error("系统错误:{}", e);
			throw new ServiceException(e);
		}
	}
	
	public String resetNewsPassword(String userAccount,String newpassword) throws ServletException{
		TSysUserinfo tcSysUserInfo;
		try {
			tcSysUserInfo = (TSysUserinfo)this.dataBaseDao.load(TSysUserinfo.class, userAccount);
			tcSysUserInfo.setUserPassword(newpassword);
			this.dataBaseDao.update(tcSysUserInfo);
			return RtnCodeConstant.RTN_CODE_SUCCESS;
		} catch (ErrorSqlException e) {
			logger.error("系统错误：{}",e);
			throw new ServletException(e);
		}
	}
	

	public List<Map> queryDeliveryExport(String param) {
		List params = new ArrayList();
		params.add("%" + param + "%");
		params.add("%" + param + "%");
		params.add("%" + param + "%");
		params.add("%" + param + "%");
		params.add("%" + param + "%");
		params.add("%" + param + "%");
		params.add("%" + param + "%");
		try {
			return this.dataBaseDao.queryForList("t_delivery_address.queryDeliveryExport", params);
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return new ArrayList();
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public int queryUserCount(String orgCode, String searchContent){
		int count=0;
		List params=new ArrayList();
		try {
			if(StringUtils.equals(null,searchContent)){
//				if(StringUtils.equals("000000",orgCode)){
//					 count=dataBaseDao.queryForInt("t_sys_userinfo.queryUserCount",null);
//				}else{
					 params.add(orgCode);
					 count=dataBaseDao.queryForInt("t_sys_userinfo.queryUserCountForOrgCode",params);
//				}
			}else{
			     params.add(searchContent);
			     params.add(searchContent);
			     count=dataBaseDao.queryForInt("t_sys_userinfo.queryUserCountForContent",params);
			}
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return count;
	}

	public List<Map> queryUser(String orgCode,String searchContent,int rows,int page) {
		List<Map> result = null;
		List params=new ArrayList();
		try {
			if(StringUtils.isEmpty(searchContent)){
				params.add(orgCode);
				params.add(rows * (page-1));
				if(StringUtils.equals(dataBaseDao.getDatabaseTypeName(), "Oracle"))
					params.add(rows * page);
				else
					params.add(rows);
				result = dataBaseDao.queryForList("t_sys_userinfo.queryUser",params);
			}else{
				params.add(searchContent);
				params.add(searchContent);
				params.add(searchContent);
				params.add(searchContent);
				params.add(searchContent);
				params.add(rows*(page-1));
				if(StringUtils.equals(dataBaseDao.getDatabaseTypeName(), "Oracle"))
					params.add(rows * page);
				else
					params.add(rows);
				result = dataBaseDao.queryForList("t_sys_userinfo.queryUserForContent",params);
			}
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Map> queryUser(String orgCode,int pageNo,int pageSize) {
		String searchContent=ServletActionContext.getRequest().getParameter("searchContent");
		List<Map> result = null;
		List param=new ArrayList();
		int maxMath=pageNo*pageSize;
		int minMath=pageNo*pageSize-pageSize+1;
		try {
			if(StringUtils.equals(null, searchContent)){
//				if(StringUtils.equals(orgCode, "000000")){
//					  param.add(maxMath);
//					  param.add(minMath);
//					result = dataBaseDao.queryForList("t_sys_userinfo.queryUser",param);
//				}else{
					param.add(orgCode);
					param.add(minMath);
				    param.add(maxMath);
					result =dataBaseDao.queryForList("t_sys_userinfo.queryUserForChildNodes",param);
//				}
			}else{
				param.add(searchContent);
				param.add(searchContent);
				param.add(minMath);
				param.add(maxMath);
				 result=dataBaseDao.queryForList("t_sys_userinfo.queryUserForContent",param);
			}
		
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public boolean getUserIdExists(String userId){
		int count=0;
		List param=new ArrayList();
		try {
			param.add(userId);
			count=dataBaseDao.queryForInt("t_sys_userinfo.ctn3", param);
		} catch (ErrorSqlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(count>0){
		   return true;
		}else{
		   return false;
		}
	}
	
	public boolean getPassWordExists(String password){
		int count=0;
		List param=new ArrayList();
		password=DescUtil.encrypt(password);
	    try {
	    	param.add(loginUser().getUserId());
	    	param.add(password);
	    	count=dataBaseDao.queryForInt("t_sys_userinfo.ctn71", param);
		} catch (ErrorSqlException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    if(count>0){
			   return true;
		}else{
			   return false;
		}
	}
	
	
	/**
	 * Function Name               queryUserInfo                                   
	 * @param userId
	 * @return          		             
	 * @throws ErrorSqlException 
	 * @description TODO(查询用户信息)
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-1-7 下午3:09:43           朱仕稳                     Initial
	 **********************************************************************
	 */
	public List<Map> queryUserInfo(String userId) throws ErrorSqlException{
		List<Map> list=this.dataBaseDao.queryForList("t_sys_userinfo.queryUserInfoByUserId", userId);
		List permissions = dataBaseDao.queryForList("t_sys_userinfo.queryUserPermissioByUserId", userId);
		Map m = new HashMap();
		m.put("permission", permissions);
		list.add(m);
		return list;
	}
	
	
	public String modifyUserForApp(String userId,String category,String value) throws ErrorSqlException{
		List param=new ArrayList();
		if(StringUtils.equals(category, "name")){
			param.add(value);
			param.add(userId);
			dataBaseDao.update("t_sys_userinfo.updateUserName",param);
		}else if(StringUtils.equals(category, "gender")){
			param.add(value);
			param.add(userId);
			dataBaseDao.update("t_sys_userinfo.updateUserGender",param);
		}else if(StringUtils.equals(category, "dept")){
			param.add(value);
			param.add(userId);
		    dataBaseDao.update("t_sys_userinfo.updateUserDept",param);
	   }else if(StringUtils.equals(category, "officetel")){
			param.add(value);
			param.add(userId);
		    dataBaseDao.update("t_sys_userinfo.updateOfficeTel",param);
	   }else if(StringUtils.equals(category, "mobile")){
		    param.add(value);
			param.add(userId);
			dataBaseDao.update("t_sys_userinfo.updateMobile",param);
	   }else if(StringUtils.equals(category, "qq")){
		    param.add(value);
			param.add(userId);
			dataBaseDao.update("t_sys_userinfo.updateUserQQ",param);
	   }else if(StringUtils.equals(category, "mail")){
		    param.add(value);
			param.add(userId);
			dataBaseDao.update("t_sys_userinfo.updateUserMail",param);
	   }else if(StringUtils.equals(category, "signature")){
		    param.add(value);
			param.add(userId);
			dataBaseDao.update("t_sys_userinfo.updateSignature",param);
	   }
		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}

	
	
	/**
	 * 
	 * Function Name               judgeMobileExists                                   
	 * @param mobile
	 * @return          		             
	 * @description 验证手机是否重复
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-6-1 下午12:01:24           黄忠                     Initial
	 **********************************************************************
	 */
	public boolean judgeMobileExists(String mobile,String userId) {
		int count=0;
		List param=new ArrayList();
		try {
			param.add(mobile);
			param.add(userId);
			count=dataBaseDao.queryForInt("t_sys_userinfo.ctnMobileExists", param);
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		if(count>0){
		   return true;
		}else{
		   return false;
		}
	}
	

	
	public String updateQyhOrgId() throws FileNotFoundException, IOException, ErrorSqlException {
//		String url = p.getAppProperties("weChatInterfaceUrl") + "/weixinCmsSiteController.do?accessTokenQy";
//		String result = HTTPClientUtils.sendGet(url);
//		JSONObject j = new JSONObject(result);
//		String msg = (String) j.get("msg");
		String msg = WeixinUtil.getAccessToken(new ParamesAPI().getCorpId(), new ParamesAPI().getSecret()).getToken();
		List<TSysOrginfo> list = (List<TSysOrginfo>) dataBaseDao.getHibernateTemplate().find(" from TSysOrginfo ", null);
		
		String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token="+msg;
		String result = HTTPClientUtils.sendGet(url);
		System.out.println(result);
		JSONObject j = new JSONObject(result);
		JSONArray arr = new JSONArray(j.get("department").toString());
		for(int i=0;i<arr.length();i++){
			JSONObject deptObj = (JSONObject) arr.get(i);
			for(TSysOrginfo tSysOrginfo:list){
				if(StringUtils.equals(tSysOrginfo.getOrgName(), deptObj.get("name").toString())){
					tSysOrginfo.setQyOrgId(Integer.parseInt(deptObj.get("id").toString()));
					dataBaseDao.update(tSysOrginfo);
					break;
				}
			}
		}
		return RtnCodeConstant.RTN_CODE_SUCCESS;
	}
	
	/**
	 * 
	 * Function Name               saveQyhOutside                                   
	 * @param userId
	 * @param userName
	 * @param mobile
	 * @param sex
	 * @param unit
	 * @return
	 * @throws IOException
	 * @throws ErrorSqlException          		             
	 * @description 微信注册/修改
	 * Modify History:              Date             Programmer       Notes
	 *                            ---------        ---------------  ---------
	 *                      2016-6-2 下午5:23:00           黄忠                     Initial
	 **********************************************************************
	 */
	public String saveQyhOutside(String userId,String userName,String mobile,String email,String orgCode,String type) throws IOException, ErrorSqlException {
		
		logger.info("Enter UserManageService saveQyhOutside type : "+type);
		
		TSysUserinfo tSysUserinfo = new TSysUserinfo();
		
		logger.info("userId :"+userId+" userName:"+userName+" mobile:"+mobile+" email:"+email+" orgCode:"+orgCode);

		if(StringUtils.isEmpty(email)||"null".equals(email)){
			email = "";
		}
		
		if("1".equals(type)) {
			//新增用户
			String sfzjh = "";
			tSysUserinfo.setUserId(userId);
			tSysUserinfo.setGender("1");
			tSysUserinfo.setIsAvailable("1");
				//设置初始密码  abcd1234
			tSysUserinfo.setUserPassword("2C608642CF08B54EDE1EEFA69941E4D4");
			tSysUserinfo.flushUpdateTime();
			tSysUserinfo.setUserName(userName);
				//设置默认头像
			tSysUserinfo.setPhotoUrl(registService.genDefaultHeadImg(tSysUserinfo.getUserId()));
			tSysUserinfo.setCreateTime(new Date());
			tSysUserinfo.setIdentificationNo(sfzjh);
			tSysUserinfo.setIdentificationTypeCode("0");
			tSysUserinfo.setOperatorName("system");
			tSysUserinfo.setSyncQyFlg("1");
			tSysUserinfo.setCompany("");
			dataBaseDao.save(tSysUserinfo);
			//保存用户角色信息   //先清
			getDataBaseDao().getJdbcTemplate().execute("delete from t_sys_userroles where userid!='admin' and userid='"+userId+"' ");
			
			List params = new ArrayList();
			params.add(orgCode);
			List<String> result = dataBaseDao.queryForList("T_SYS_ROLEINFO.queryRoleInfoByOrgCode", params);
			//保存用户关联角色数据
			for (String str : result) {
				TSysUserroles userRoles = new TSysUserroles();
				userRoles.setRoleId(str);
				userRoles.setUserId(userId);
				userRoles.setOperatorAccount("admin");
				userRoles.setOperatorName("system");
				userRoles.setUserRoleId(UUID.randomUUID().toString());
				userRoles.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
				userRoles.flushUpdateTime();
				
				dataBaseDao.save(userRoles);
			}
			
			//同步到企业号
			String JOBPOSITION = "";
			TSysOrginfo tSysOrginfo = (TSysOrginfo) dataBaseDao.load(TSysOrginfo.class, orgCode);
			String QYORGID = tSysOrginfo.getQyOrgId() + "";
			WeixinUtil.syncUserToQyhByMobile(userId,userName,QYORGID.toString(),JOBPOSITION,"1",mobile,  email);
			
		}else if("2".equals(type)) {
			
			TSysUserinfo t = (TSysUserinfo) dataBaseDao.load(TSysUserinfo.class, userId);
			t.setUserId(userId);
			t.setUserName(userName);
			t.setMobile(mobile);
			t.setEmail(email);
			dataBaseDao.update(t);
			
			getDataBaseDao().getJdbcTemplate().execute("delete from t_sys_userroles where userid!='admin' and userid='"+userId+"' ");

			List params = new ArrayList();
			params.add(orgCode);
			List<Map> result = dataBaseDao.queryForList("T_SYS_ROLEINFO.queryRoleInfoByOrgCode", params);
			//保存用户关联角色数据
			for (Map str : result) {
				TSysUserroles userRoles = new TSysUserroles();
				userRoles.setRoleId(str.get("ROLEID").toString());
				userRoles.setUserId(userId);
				userRoles.setOperatorAccount("admin");
				userRoles.setOperatorName("system");
				userRoles.setUserRoleId(UUID.randomUUID().toString());
				userRoles.setIsAvailable(DBConstant.DB_STATUS_ABLCE);
				userRoles.flushUpdateTime();
				
				dataBaseDao.save(userRoles);
			}
			
			//同步到企业号
			String JOBPOSITION = "";
			TSysOrginfo tSysOrginfo = (TSysOrginfo) dataBaseDao.load(TSysOrginfo.class, orgCode);
			String QYORGID = tSysOrginfo.getQyOrgId() + "";
			WeixinUtil.syncUserUpdate(userId,userName,QYORGID.toString(),JOBPOSITION,"0",mobile,email);
			
		}
		
		
		
		logger.info("Exit UserManageService saveQyhOutside ");
		return RtnCodeConstant.RTN_CODE_SUCCESS;
		
		
	}

	public List<Map> queryUserSearch(String orgCode, int page, int pageSize, String searchContent) {
		List<Map> result = null;
		List param=new ArrayList();
		int maxMath=page*pageSize;
		int minMath;
		if(StringUtils.equals(dataBaseDao.getDatabaseTypeName(), "Oracle"))
			minMath=page*pageSize-pageSize+1;
		//mysql
		else
			minMath=page*pageSize-pageSize+1 - 1;
		try {
			if(StringUtils.equals(null, searchContent)){
//				if(StringUtils.equals(orgCode, "000000")){
//					  param.add(maxMath);
//					  param.add(minMath);
//					result = dataBaseDao.queryForList("t_sys_userinfo.queryUser",param);
//				}else{
					param.add(orgCode);
					param.add(minMath);
				    param.add(maxMath);
					result =dataBaseDao.queryForList("t_sys_userinfo.queryUserForChildNodes",param);
//				}
			}else{
				param.add(searchContent);
				param.add(searchContent);
				param.add(minMath);
				param.add(maxMath);
				 result=dataBaseDao.queryForList("t_sys_userinfo.queryUserForContent",param);
			}
		
		} catch (ErrorSqlException e) {
			e.printStackTrace();
		}
		return result;
	}
	
}

